/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.workflow.service.impl;

import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.workflow.domain.ActRuTask;
import me.zhengjie.modules.workflow.service.dto.ActRuTaskQueryCriteria;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.workflow.repository.ActRuTaskRepository;
import me.zhengjie.modules.workflow.service.ActRuTaskService;
import me.zhengjie.modules.workflow.service.dto.ActRuTaskDto;
import me.zhengjie.modules.workflow.service.mapstruct.ActRuTaskMapper;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author wzp
* @date 2021-05-08
**/
@Service
@RequiredArgsConstructor
public class ActRuTaskServiceImpl implements ActRuTaskService {

    private final ActRuTaskRepository actRuTaskRepository;
    private final ActRuTaskMapper actRuTaskMapper;
    private final UserService userService;

    @Override
    public Map<String,Object> queryAll(ActRuTaskQueryCriteria criteria, Pageable pageable){
        UserDto userDto = userService.findById(SecurityUtils.getCurrentUserId());
        // 拼装角色ID集合
        List<String> groupIds = new ArrayList<String>();
        Set<RoleSmallDto> roles = userDto.getRoles();
        if(!roles.isEmpty()){
            roles.forEach(item->{
                groupIds.add(String.valueOf(item.getId()));
            });
        }

        // 分页查询用户待办任务：用户id以及用户所有的角色ID
        Page<ActRuTask> page = actRuTaskRepository.findTodoTask(String.valueOf(userDto.getId()),StringUtils.join(groupIds.toArray(), ","),pageable);
        // 处理显示名称
        page.getContent().forEach(item->{
            // 查询任务执行人名称以及任务持有者名称
            if(item.getAssignee() != null){
                String assigneeName =  userService.findUserNameById(item.getAssignee());
                item.setAssigneeName(assigneeName);
            }
            if(item.getOwner() != null){
                String ownerName =  userService.findUserNameById(item.getOwner());
                item.setOwnerName(ownerName);
            }
        });
        return PageUtil.toPage(page.map(actRuTaskMapper::toDto));
    }

    @Override
    public List<ActRuTaskDto> queryAll(ActRuTaskQueryCriteria criteria){
        return actRuTaskMapper.toDto(actRuTaskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public ActRuTaskDto findById(String id) {
        ActRuTask actRuTask = actRuTaskRepository.findById(id).orElseGet(ActRuTask::new);
        ValidationUtil.isNull(actRuTask.getId(),"ActRuTask","id",id);
        return actRuTaskMapper.toDto(actRuTask);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActRuTaskDto create(ActRuTask resources) {
        resources.setId(IdUtil.simpleUUID()); 
        return actRuTaskMapper.toDto(actRuTaskRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ActRuTask resources) {
        ActRuTask actRuTask = actRuTaskRepository.findById(resources.getId()).orElseGet(ActRuTask::new);
        ValidationUtil.isNull( actRuTask.getId(),"ActRuTask","id",resources.getId());
        actRuTask.copy(resources);
        actRuTaskRepository.save(actRuTask);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            actRuTaskRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ActRuTaskDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ActRuTaskDto actRuTask : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("版本", actRuTask.getRev());
            map.put("任务对应执行流ID", actRuTask.getExecutionId());
            map.put("流程实例ID", actRuTask.getProcInstId());
            map.put("任务对应流程定义ID", actRuTask.getProcDefId());
            map.put("任务名称", actRuTask.getName());
            map.put("父任务ID", actRuTask.getParentTaskId());
            map.put("任务描述", actRuTask.getDescription());
            map.put("taskDefKey",  actRuTask.getTaskDefKey());
            map.put("任务拥有人", actRuTask.getOwner());
            map.put("需要执行任务人", actRuTask.getAssignee());
            map.put("任务被委派的状态", actRuTask.getDelegation());
            map.put("优先级", actRuTask.getPriority());
            map.put("创建时间", actRuTask.getCreateTime());
            map.put("预定日期", actRuTask.getDueDate());
            map.put("任务类型", actRuTask.getCategory());
            map.put("任务状态", actRuTask.getSuspensionState());
            map.put("多租户", actRuTask.getTenantId());
            map.put("表单KEY", actRuTask.getFormKey());
            map.put("任务提醒时间", actRuTask.getClaimTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}